package com.iqismart.shorturl.websocket;

import com.iqismart.shorturl.model.EntityUser;
import com.iqismart.shorturl.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description
 * @Auther sty
 * @createTime 2019-01-11 17:27
 */
@ServerEndpoint(value = "/websocket/{param}",configurator=GetHttpSessionConfigurator.class)
@Component
public class MyWebSocket {

    @Autowired
    private UserRepository userRepository;

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    public static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();

    private static Map<String, HttpSession> socketNumb = new ConcurrentHashMap<String, HttpSession>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    private String userName = "";
    private Long userId;
    private Long lastActive = System.currentTimeMillis();

    //给所有人发消息
    public static void sendMessage(Message message){
        if(message.getFrom() == 0 && message.getTo() == 0){
            for(MyWebSocket myWebSocket:webSocketSet){
                try {
                    Long sockerUid = myWebSocket.getUserId();
                    Long hiddenForUid = message.getHiddenForUid();
                    if(sockerUid != null && hiddenForUid != null){
                        if(sockerUid.equals(hiddenForUid)) {
                            //不给自己发自己的消息
                            myWebSocket.sendMessage("你"+message.getMessage() + " (刚刚) ");
                        }else{
                            myWebSocket.sendMessage(message.getHiddenForUserName()+message.getMessage() + " (刚刚) ");
                        }
                    }else{
                        myWebSocket.sendMessage(message.getHiddenForUserName()+message.getMessage() + " (刚刚) ");
                    }


                } catch (IOException e) {
                    //e.printStackTrace();
                }
            }
        }

    }

    //给所有人发消息
    public static void sendMessageToAll(String message){

        for(MyWebSocket myWebSocket:webSocketSet){
            try {
                myWebSocket.sendMessage(message);
            } catch (Exception e) {
                //e.printStackTrace();
            }
        }

    }

    //给某个人发消息
    public static void sendMessageToAll(Long userId,String message){
        for(MyWebSocket myWebSocket:webSocketSet){
            try {
                if(myWebSocket.userId == userId){
                    myWebSocket.sendMessage(message);
                }

            } catch (IOException e) {
                //e.printStackTrace();
            }
        }
    }


    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(@PathParam(value="param") String param,Session session, EndpointConfig config) {
        this.session = session;
        this.userId = (Long) config.getUserProperties().get("uid");

        String username = "";
        if(userId != null && userId > 0){
            try {
                final EntityUser entityUser = userRepository.findById(userId).get();
                username = entityUser.getUsername();
            } catch (Exception e) {
                //e.printStackTrace();
                username = "游客"+param;
            }
        }else{
            username = "游客"+param;
        }

        this.setUserName(username);

        webSocketSet.add(this);     //加入set中
                 //在线数加1
        System.out.println(username+"加入！当前在线人数为" + addOnlineCount());


    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        System.out.println(getUserName()+"连接关闭！当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);

        //群发消息
        for (MyWebSocket item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发生错误时调用
     * */
     @OnError
     public void onError(Session session, Throwable error) {
     System.out.println("发生错误");
     error.printStackTrace();
     }

     public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
        this.lastActive = System.currentTimeMillis();
        //this.session.getAsyncRemote().sendText(message);
     }


     /**
      * 群发自定义消息
      * */
    public static void sendInfo(String message) throws IOException {
        for (MyWebSocket item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static int getOnlineCount() {
        return onlineCount.get();
    }

    public static int addOnlineCount() {
        return onlineCount.incrementAndGet();
    }

    public static void subOnlineCount() {
        if(MyWebSocket.onlineCount.get() <= 0){
            MyWebSocket.onlineCount.set(0);
            return;
        }
        MyWebSocket.onlineCount.decrementAndGet();
    }

    public static void setOnlineCount(int onlineCount) {
        MyWebSocket.onlineCount.set(onlineCount);
    }

    public static CopyOnWriteArraySet<MyWebSocket> getWebSocketSet() {
        return webSocketSet;
    }

    public static void setWebSocketSet(CopyOnWriteArraySet<MyWebSocket> webSocketSet) {
        MyWebSocket.webSocketSet = webSocketSet;
    }

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    public String getUserName() {
        return userName;
    }

    public Long getLastActive() {
        return lastActive;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        MyWebSocket that = (MyWebSocket) o;

        return userName.equals(that.userName);
    }

    @Override
    public int hashCode() {
        return userName.hashCode();
    }
}